#include "GLColorDataFromVertexWindow.h"

GLColorDataFromVertexWindow::GLColorDataFromVertexWindow(QWidget* parent)
	: BaseOpenGLWindow(parent)
{
	this->setWindowTitle("从顶点着色器传递颜色值到片元着色器");
	QHBoxLayout* hLayout = new QHBoxLayout(this);
	QPushButton* btnRed = new QPushButton(this);
	btnRed->setText("Y轴颠倒");
	QPushButton* btnGreen = new QPushButton(this);
	btnGreen->setText("X轴颠倒");
	QPushButton* btnBlue = new QPushButton(this);
	btnBlue->setText("X轴平移");
	hLayout->addWidget(btnRed);
	hLayout->addWidget(btnGreen);
	hLayout->addWidget(btnBlue);
	hLayout->setAlignment(Qt::AlignTop);

	connect(btnRed, &QPushButton::clicked, [=]() {
		changeTriStatus(1);
		});

	connect(btnGreen, &QPushButton::clicked, [=]() {
		changeTriStatus(2);
		});

	connect(btnBlue, &QPushButton::clicked, [=]() {
		changeTriStatus(3);
		});
}
void GLColorDataFromVertexWindow::initializeGL() {
	this->initializeOpenGLFunctions();
	glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT);

	float vertices[] = {
		// 位置              // 颜色
		 0.5f, -0.5f, 0.0f,  1.0f, 0.0f, 0.0f,   // 右下
		-0.5f, -0.5f, 0.0f,  0.0f, 1.0f, 0.0f,   // 左下
		 0.0f,  0.5f, 0.0f,  0.0f, 0.0f, 1.0f    // 顶部
	};
	glGenVertexArrays(1, &VAO);
	glGenBuffers(1, &VBO);
	glBindVertexArray(VAO);

	//创建VBO并创建存放顶点数据的内存
	glBindBuffer(GL_ARRAY_BUFFER, VBO);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
	//位置数据
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
	glEnableVertexAttribArray(0);
	//颜色数据
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
	glEnableVertexAttribArray(1);

	//小程序
	programId = buildAttachShaderAndReturnProgramId(":/QtForOpenCV4Tool/shader/vertex_color.vert",
		":/QtForOpenCV4Tool/shader/vertex_color.frag");
}
void GLColorDataFromVertexWindow::resizeGL(int w, int h) {
	glViewport(0, 0, w, h);
}
void GLColorDataFromVertexWindow::paintGL() {
	glUseProgram(programId);
	GLint mLocation = glGetUniformLocation(programId, "mX");
	glUniform1f(mLocation, mX);
	GLint mLocation1 = glGetUniformLocation(programId, "mY");
	glUniform1f(mLocation1, mY);
	GLint mLocation2 = glGetUniformLocation(programId, "mXT");
	glUniform1f(mLocation2, mXT);
	switch (type) {
	case 1: {
		mX = -1.0f;
		GLint mLocation = glGetUniformLocation(programId, "mX");
		glUniform1f(mLocation, mX);
		break;
	}
	case 2: {
		mY = -1.0f;
		GLint mLocation = glGetUniformLocation(programId, "mY");
		glUniform1f(mLocation, mY);
	}
		  break;
	case 3: {
		mXT = 0.25f;
		GLint mLocation = glGetUniformLocation(programId, "mXT");
		glUniform1f(mLocation, mXT);
	}
		  break;
	}
	glBindVertexArray(VAO);
	glDrawArrays(GL_TRIANGLES, 0, 3);
}

void GLColorDataFromVertexWindow::changeTriStatus(int type) {
	this->type = type;
	mY = 1.0f;
	mX = 1.0f;
	mXT = 0.0f;
	update();
}
GLColorDataFromVertexWindow::~GLColorDataFromVertexWindow()
{
}
